package com.lixiaoyi.config.security.handle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lixiaoyi.config.redis.RedisService;
import com.lixiaoyi.entity.User;
import com.lixiaoyi.utils.JwtUtils;
import com.lixiaoyi.utils.LoginResult;
import com.lixiaoyi.utils.ResultCode;
import com.sun.xml.internal.bind.api.impl.NameConverter;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author 李小毅
 * @Description
 * @Date 2022-07-01
 */

// 登录认证成功处理器类
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource  // 注入token
    private JwtUtils jwtUtils;

    @Resource
    private RedisService redisService;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        // 设置响应的编码格式
        response.setContentType("application/json;charset=utf-8");
        // 获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        // 获取当前登录的用户信息  强转成User类型
        User user = (User)authentication.getPrincipal();

        // 生成token
        String token = jwtUtils.generateToken(user);
        // 设置token的签名密钥以及过期时间
        long expireTime = Jwts.parser()
                .setSigningKey(jwtUtils.getSecret())  // 设置密钥
                .parseClaimsJws(token.replace("jwt_", ""))
                .getBody().getExpiration().getTime();// 设置过期时间
        // 创建LoginResult 登陆对象
        LoginResult loginResult = new LoginResult(user.getId(), ResultCode.SUCCESS, token, expireTime);


        // 将当前对象转换成JSON格式  并消除循环引用
        String result = JSON.toJSONString(loginResult, SerializerFeature.DisableCircularReferenceDetect);
        outputStream.write(result.getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();

        // 将token信息保存到redis中
        String tokenKey = "token_" + token;
        redisService.set(tokenKey,token,jwtUtils.getExpiration() / 1000);
    }
}
















